# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：get_ts_video.py
#日期：2020-02-15
#备注：通过ffmpeg库处理视频信息处理实际遇到的问题
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import urllib.request
import os
import time
from Crypto.Cipher import AES
from pycacho.cachobase.files_select import get_files
from pacong.pachong_config import headers


# 不加密 vn-->视频名称，num-->视频切割数量
def get_videos(url,vn,sm,tm,length):
    save_path = 'F:\image\\' + vn + '\\'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    for i in range(sm,tm):
        name = ('%0'+length+'d')%(i) + '.ts'
        fur_url = url + vn + name
        time.sleep(5)
        print('开始下载视频频段-->' + fur_url)
        req = urllib.request.Request(url=fur_url, headers=headers)
        video = urllib.request.urlopen(req, timeout=120)
        mp4 = video.read()
        with open(save_path + name, 'ab') as f:
            f.write(mp4)


# 加密：vn-->视频名称，num-->视频切割数量
def all_video(url,vn,key,sm,tm,length):
    sTime = time.time()
    cryptor = AES.new(key, AES.MODE_CBC, key)
    save_path = 'F:\image\\' + vn + '\\'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    for i in range(sm,tm):
        name = ('%0'+length+'d')%(i) + '.ts'
        fur_url = url + vn + name
        time.sleep(5)
        print('开始下载视频频段-->' + fur_url)
        req = urllib.request.Request(url=fur_url, headers=headers)
        video = urllib.request.urlopen(req, timeout=120)
        mp4 = video.read()
        with open(save_path + name, 'ab') as f:
            f.write(cryptor.decrypt(mp4))

    eTime = time.time()
    s = eTime - sTime
    print('单线程花费的时间为：%.2f秒' % (s))


# vn-->视频名称，num-->视频切割数量
def one_video(n):
    cryptor = AES.new(key, AES.MODE_CBC, key)
    name = '/qbDBUkjg5803' + '%03d'%(n) + '.ts'
    fur_url = url + vn + name
    print('开始下载视频频段-->' + fur_url)
    #file = open(save_path + name, "wb")
    req = urllib.request.Request(url=fur_url, headers=headers)
    video = urllib.request.urlopen(req, timeout=40)
    mp4 = video.read()                                 # 将文件转换为bytes格式
    save_path = 'F:\image\\' + vn + '\\'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    with open(save_path + name, 'ab') as f:
        f.write(cryptor.decrypt(mp4))


def change_video(vn):
    sTime = time.time()
    save_path = 'F:\image\\' + vn + '\\'
    os.chdir(save_path)
    output_video = 'F:\image\\other\\' + vn + '.mp4'
    info = get_files(save_path, 'ts')
    change = ''
    for file in info:
        change = change + file.split(vn +'\\')[1] + '|'
    videos = ('concat:' + change)[:-1]
    exec_concat = 'ffmpeg -i "%s" -c:a copy -c:v copy -y ' % (videos) + output_video  # -s 540x960
    print(exec_concat)
    os.system(exec_concat)

    eTime = time.time()
    s = eTime - sTime
    print('花费的时间为：%.2f秒' % (s))


def get_info():
    videos = []
    with open('F:\image\\index.txt', 'r', encoding='utf-8') as fp:
        for line in fp.readlines():
            line = line.lstrip().replace(' ','').replace('\n','')
            if line[0:1] != '#':
                info = line.split('|')
                videos.append(info)
    #print(videos)
    return videos


def main(type):
    video_info = get_info()
    for s in video_info:
        url = s[0]
        vn = s[1]
        key = s[2]
        tm = int(s[3])
        length = str(s[4])            # 分段视频数量长度 比如1000就为4
        print(url,vn,key,tm)
        if type == 0:
            all_video(url,vn, key,29, tm,length)
        elif type == 1:
            get_videos(url, vn, 27, tm, length)
        else:
            change_video(vn)

if __name__ == '__main__':
    vn = 'hls'
    key = "407d5980b98e9afb"
    url = 'https://bobo.kkpp.space/20170814/NTnl7PcY/'
    sm = 355
    tm = 601
    main(1)           # 0-加密视频，1-不加密视频，其他-视频合并
    #one_video(1)
    #print(url)
    #all_video(url,vn,key,sm,tm)
    #change_video(vn)
